namespace FIREFLYX {

    export class ShaderUtil {
        /**
         * 设置 材质的属性值, 用于对应shader unifrom 全局字段
         * @param name 属性名字
         * @param value 值
         * @returns 设置是否成功
         */
        public static SetProperty(propertyMap: ShaderPropertyMap, name: string, value: UniformUserValue | UniformUserValue[]) {
            if (!name) {
                console.log(`setProperty invalid , property name is null.`);
                return false;
            }
            if (value == propertyMap[name]) {
                return false;
            }
            if (value == null) {
                delete propertyMap[name];
                return false;
            }

            //是否是 materialValue[]?
            if (!Array.isArray(value)) {
                propertyMap[name] = this.GetPropertyUseValue(value);
            } else {
                let len = value.length;
                let arr = propertyMap[name] as (BufferSource | TextureBase)[];
                if (arr == null) {
                    arr = propertyMap[name] = [];
                }
                arr.length = len;
                for (let i = 0; i < len; i++) {
                    const subVal = value[i];
                    arr[i] = this.GetPropertyUseValue(subVal);
                }
            }

            return true;
        }

        private static GetPropertyUseValue(val: UniformUserValue): BufferSource | TextureBase {
            if (typeof (val) == `object`) {
                if ((val as any).byteLength != null) {
                    return val as BufferSource;
                } else if ((val as any).asArray != null) {
                    const arr = (val as any).asArray() as (number[] | Float32Array);
                    return Array.isArray(arr) ? new Float32Array(arr) : arr;
                }

                //纹理
                return val as TextureBase;
            }

            //is number
            return new Float32Array([val]);
        }
    }
}